// Copyright (c) 2002 HTHK
//******************************************************************/
//Modification History
//******************************************************************/
//CR log no 1054: By Oscar Bai  Date:2003/02
//******************************************************************/
/*--------------------------------------------------------------
 * Modification History
 *--------------------------------------------------------------
 * CRLOG	: CR1528
 * Fix		: Sox Login control 
 * By		: PH, HPMS
 * Date		: 26-Feb-2005
 *--------------------------------------------------------------
 */

package admin;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;
import java.util.Date;
import java.text.*;
import java.sql.*;

import com.ffpc.servlet.*;
import com.ffpc.sql.*;
import com.ffpc.struts.StrutsMessage;
import com.ffpc.util.DateFormatter;
import com.ffpc.util.NumberFormatter;

import admin.JisEncrypt;
import admin.system.sysparam.*;
import admin.system.user.UserBean;
import admin.system.user.UserProcess;
/* CR1528 */
/**
 * A Class class.
 * <P>
 * @author HTHK
 */

public class LoginServlet
  extends DBServlet {

  @Override
protected String perform(  HttpServletRequest request,
                             HttpServletResponse response,
                             StrutsMessage message)
    throws  ServletException,
            IOException,
            SQLException,
            DataException,
            Exception
  {

     //CR log no 1054 begin of:

      String tempIna_date="";
      String tempExpiry_date="";
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss",Locale.US);
      Date tempDate= null;

     //CR log no 1054 end of:
      
      UserBean user = UserProcess.createBean();
      user.setUser_id(request.getParameter("user_id"));

     //CR log no 1054:
     // remove reason: get user info just by user_id
     // user.setPasswd(request.getParameter("passwd"));

      UserBean[] users = UserProcess.find(this.getConnection(),user);

      if (users==null || users.length!=1)
      {
        message.setMessage("No such user exist, please input again.");
        return "Login.jsp";
      }
	  /* CR1528 */
	  else if ( isLocked(this.getConnection(), users[0]) )
	  {
		  message.setMessage("User A/C is Locked, please contact system administrator");
		  return "Login.jsp";
	  }
	  /* CR1528 */
      else
      {
        System.out.println("User ID: " + users[0].getUser_id() );
        System.out.println("JIS User's Request Group : " + users[0].getRequest_group() );
        this.getSession().setAttribute("user",users[0]);

        //CR log no 1054 begin of: Check Password validity

        //CR Log no:no begin of: set connection
        JisEncrypt jis_encrypt = new JisEncrypt(this.getConnection());
        //CR Log no:no end of
           
        if (jis_encrypt.checkPWD(request.getParameter("passwd"),users[0].getPasswd()))
        { 
          tempIna_date=users[0].getInactive_date();

        //CR log no 1054 end of  

          //CR log no 1054 begin of: Check the inactive date if user passwd is valid
          if ((tempIna_date!=null)&&(tempIna_date.length()>1)){
            try{
           //CR 2003-3-7
//              tempDate = new Date(sdf.parse(tempIna_date).getTime());

             tempDate = new Date(DateFormatter.parse(tempIna_date).getTime());
             
            }catch(ParseException e){
              System.out.println(e.toString());         
            }
               
            if (tempDate.compareTo(new Date())<=0){
              message.setMessage("This User Account has been Deactivated already!Please try another!");
              return "Login.jsp"; 
            }            
          }
          //CR log no 1054 end of                

          //CR log no 1054 begin of: Check the Expiry date
          tempExpiry_date=users[0].getPass_exp_date();                      

          if ((tempExpiry_date!=null)&&(tempExpiry_date.trim().length()>1)){

          //CR 2003-3-7
//            tempDate=new Date(sdf.parse(tempExpiry_date).getTime());

            tempDate=new Date(DateFormatter.parse(tempExpiry_date).getTime());

			/* CR1528 */
			LoginSuccess(this.getConnection(), users[0]);
			/* CR1528 */

            if (tempDate.compareTo(new Date())<=0){
              message.setMessage("Your password has been expired,please change your password now.");
              return "LoginChangePW.jsp";         
            }
          }
           
          users[0].setAuthenticated(true);
          return "servlet/admin.menu.MenuServlet";
        }else{
           message.setMessage("Invalid password, please input again.");
		   /* CR1528 */
		   LoginFailed(this.getConnection(), users[0]);
		   /* CR1528 */
           return "Login.jsp";
        }//end check pw

       //CR log no 1054 end of                

      }
  }

  // function override
  @Override
protected boolean isLogin()
  {
      return true;
  }

  /* CR1528 */
  /**
   * get SysVar: PASSWD_HISTORY 
   * return the sysval in int format
   *
  */
  public static int MaxTrial(Connection con)
    throws DataException
  {
	int max_record				= 5; //default value
    SysParamBean srtn			= SysParamProcess.createBean();

    srtn.setSys_Param_name("MAX_TRIAL");

    SysParamBean[] rtnlist		= SysParamProcess.find(con, srtn);
    
    if( rtnlist.length == 0 )	return max_record;

    srtn						= rtnlist[0];
	try
	{
  		max_record					= NumberFormatter.parseInt( srtn.getSys_Param_value() );		
	}
	catch (Exception e)
	{
		System.err.println(" LoginServlet.MaxTrial() error = " + e.toString() );
	}
    return max_record;
  }

  /**
   * check a/c is locked ?
   * 
   * true - locked
   */
   public static boolean isLocked(Connection con, UserBean v_user) {
	 try
	 {
	   // active flag is dummy?? this flag does not display in user maintenance
	   //if ( !v_user.getActive().equalsIgnoreCase("Y") ) return true; // inactive
	   if ( v_user.getInactive_date() == null || v_user.getInactive_date().equals("") ) {
	   }
	   else {
	   	   Date inactive_date = new Date(DateFormatter.parse(v_user.getInactive_date()).getTime());
		   if ( inactive_date.compareTo( new Date() ) <=0 ) return true;								// inactive
	   }
	   if ( ! (MaxTrial(con) > NumberFormatter.parseInt(v_user.getLogin_trial()) )  ) return true;	// reached max logon trial
	   return false;
	 }
	 catch (Exception e)
	 { 
		 System.err.println("LoginServlet : isLocked error = " + e.toString() );
		 return false;
	 }
   }

  /**
   * LoginFailed, user Login_trial + 1 
   *
   */
   public static void LoginFailed(Connection con, UserBean v_user) {
	 try
	 {
	 	UserBean t_user			= v_user;
		int count				= NumberFormatter.parseInt( t_user.getLogin_trial() ) + 1;
		t_user.setLogin_trial( ""+count );
		UserProcess.update(con, t_user);
	 }
	 catch (Exception e)
	 {
 		System.err.println("LoginServlet : LoginFailed error = " + e.toString() );
	 }
   }

  /**
   * LoginSuccess, user Login_trial reset to 0 
   *
   */
   public static void LoginSuccess(Connection con, UserBean v_user) {
	 try
	 {
	 	UserBean t_user			= v_user;
		if( NumberFormatter.parseInt( t_user.getLogin_trial() ) > 0 ) {
			t_user.setLogin_trial( "0" );
			UserProcess.update(con, t_user);
		}
	 }
	 catch (Exception e)
	 {
 		System.err.println("LoginServlet : LoginSuccess error = " + e.toString() );
	 }
   }
  /* CR1528 */

}


 